<?php

class UserSignupForm extends BaseForm {
  const FORM_NAME               = 'frm';

  const FIELD_FIRST_NAME        = 'first_name';
  const FIELD_LAST_NAME         = 'last_name';
  const FIELD_EMAIL             = 'email';
  const FIELD_PASSWORD          = 'password';
  const FIELD_CONFIRM_PASSWORD  = 'confirm_password';
  const FIELD_ADDRESS           = 'address';
  const FIELD_CITY              = 'city';
  const FIELD_STATE_ID          = 'state_id';
  const FIELD_POST_CODE         = 'post_code';
  const FIELD_PHONE             = 'phone';
  const FIELD_GENDER            = 'gender';
  const FIELD_DATE_OF_BIRTH     = 'date_of_birth';
  const FIELD_CINEMA            = 'cinema';
  const FIELD_MOVIE_PREFERENCE  = 'movie_preference';
  const FIELD_ALERT_LAUNCH      = 'alert_launch';
  const FIELD_ALERT_DEALS       = 'alert_deals';

  private $isMemberUpdate = null;
  
  public static $moviePreferences = array(
        Constants::MOVIE_ACTION_ADVENTURE => 'Action / Adventure',
        Constants::MOVIE_ROMANTIC_COMEDY => 'Romantic Comedy',
        Constants::MOVIE_HORROR => 'Horror',
        Constants::MOVIE_CHILDRENS => 'Children\'s',
        Constants::MOVIE_ANIMATION => 'Animation',
        Constants::MOVIE_DRAMA => 'Drama',
        Constants::MOVIE_COMEDY => 'Comedy'
    );

  public function  __construct($isMemberUpdate = false) {
    $this->isMemberUpdate = $isMemberUpdate;
    parent::__construct();
  }

  public function configure() {
    $arrUserGroupsIds = USER_GROUPTable::getInstance()->findAllArray();
    $arrGender = StringUtil::getGenderArray();
    $arrStates = STATETable::getInstance()->findAllArray(true);

    $arrYears = array();
    for ($i=(date('Y')-10); $i>=(date('Y')-100); $i--) {
      $arrYears[$i] = $i;
    }

    $arrMonths = array();
    for ($i=1; $i<=12; $i++) {
      $arrMonths[$i] = date('M', mktime(1,1,1,$i));
    }

    $arrDays = array();
    for ($i=1; $i<=31; $i++) {
      $arrDays[$i] = date('d', mktime(1,1,1,1,$i));
    }
    
    $arrCinemaList = CINEMA_LISTTable::getInstance()->findAllArray(true);

    $widgets = array(
            self::FIELD_EMAIL               => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_PASSWORD            => new sfWidgetFormInputPassword(array(), array('maxlength' => 30)),
            self::FIELD_CONFIRM_PASSWORD    => new sfWidgetFormInputPassword(array(), array('maxlength' => 30)),
            self::FIELD_FIRST_NAME          => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_LAST_NAME           => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_ADDRESS             => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_CITY                => new sfWidgetFormInput(array(), array('maxlength' => 100)),
            self::FIELD_STATE_ID            => new sfWidgetFormSelect(array('choices' => $arrStates), array('multiple' => false, 'expand' => true)),
            self::FIELD_POST_CODE           => new sfWidgetFormInput(array(), array('maxlength' => 20)),
            self::FIELD_PHONE               => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_GENDER              => new sfWidgetFormSelectRadio(array('formatter' => array('FormWidgetFormatter', 'formatGender'), 'choices' => $arrGender), array()),
            self::FIELD_DATE_OF_BIRTH       => new sfWidgetFormDate(array('format' => '%day% %month% %year%', 'years' => $arrYears, 'months' => $arrMonths, 'days' => $arrDays)),
            self::FIELD_CINEMA              => new sfWidgetFormSelect(array('choices' => $arrCinemaList), array('multiple' => false, 'expand' => true)),
            self::FIELD_MOVIE_PREFERENCE    => new sfWidgetFormInputHidden(),
            self::FIELD_ALERT_LAUNCH        => new sfWidgetFormInputCheckbox(array('value_attribute_value' => 1)),
            self::FIELD_ALERT_DEALS         => new sfWidgetFormInputCheckbox(array('value_attribute_value' => 1))
    );
    
    foreach (self::$moviePreferences as $key => $val) {
      $widgets[self::FIELD_MOVIE_PREFERENCE . '_' . $key] = new sfWidgetFormInputCheckbox(array('value_attribute_value' => $val));
    }

    $labels = array(
            self::FIELD_EMAIL               => 'Email Address',
            self::FIELD_PASSWORD            => 'Password',
            self::FIELD_CONFIRM_PASSWORD    => 'Confirm Password',
            self::FIELD_FIRST_NAME          => 'First Name',
            self::FIELD_LAST_NAME           => 'Last Name',
            self::FIELD_ADDRESS             => 'Address',
            self::FIELD_CITY                => 'City',
            self::FIELD_STATE_ID            => 'State',
            self::FIELD_POST_CODE           => 'Post Code',
            self::FIELD_PHONE               => 'Phone',
            self::FIELD_GENDER              => 'Gender',
            self::FIELD_DATE_OF_BIRTH       => 'Date of Birth',
            self::FIELD_CINEMA              => 'Favourite Cinema',
            self::FIELD_MOVIE_PREFERENCE    => 'What movies do you like?',
            self::FIELD_ALERT_LAUNCH        => 'Yes, send me email updates about Supertain\'s launch',
            self::FIELD_ALERT_DEALS         => 'Yes, send me email updates on special offers, deals'
    );

    $this->setWidgets($widgets);
    $this->widgetSchema->setLabels($labels);

    $validators = array(
            self::FIELD_EMAIL         => new sfValidatorEmail(array('trim' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_EMAIL])), 'invalid' => LangUtil::getText('error_invalid', array($labels[self::FIELD_EMAIL])))),
            self::FIELD_FIRST_NAME    => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required',array($labels[self::FIELD_FIRST_NAME])))),
            self::FIELD_LAST_NAME     => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required',array($labels[self::FIELD_LAST_NAME])))),            
            self::FIELD_POST_CODE     => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required',array($labels[self::FIELD_POST_CODE]))))
    );

    if (!$this->isMemberUpdate) {
      $validators[self::FIELD_PASSWORD] = new sfValidatorString(array('trim' => true, 'min_length' => 6), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_PASSWORD])), 'min_length' => $labels[self::FIELD_PASSWORD] . ' should be at least 6 characters long'));
    }
    $this->setValidators($validators);
    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'postValidator'))));

    $this->widgetSchema->setNameFormat(self::FORM_NAME . '[%s]');

    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->validatorSchema->setOption('filter_extra_fields', false);
  }

  public function postValidator($validator, $values) {
    if (!$this->isMemberUpdate) {
      if (strlen($values[self::FIELD_PASSWORD]) >= 6 && $values[self::FIELD_PASSWORD] != $values[self::FIELD_CONFIRM_PASSWORD]) {
        $error = new sfValidatorError($validator, LangUtil::getText('error_mismatch_conf_password'));
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_CONFIRM_PASSWORD => $error));
      }

      $user = USERTable::getInstance()->findByUsername($values[self::FIELD_EMAIL]);
      if ($user instanceof USER) {
        $error = new sfValidatorError($validator, LangUtil::getText('error_already_exist', array('Email Address / Username')));
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_EMAIL => $error));
      }

      $resp = recaptcha_check_answer(sfConfig::get('app_recaptcha_api_key_private'), ServerUtil::getUserIp(), $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);

      if (!$resp->is_valid) {
        throw new sfValidatorError($validator, LangUtil::getText('error_captcha'));
      }
    }
    return $values;
  }

  public function populateData(USER $user) {
    $this->setDefault(self::FIELD_EMAIL, $user->getEmail());
    $this->setDefault(self::FIELD_FIRST_NAME, $user->getFirstName());
    $this->setDefault(self::FIELD_LAST_NAME, $user->getLastName());
    $this->setDefault(self::FIELD_ADDRESS, $user->getAddress());
    $this->setDefault(self::FIELD_CITY, $user->getCity());
    $this->setDefault(self::FIELD_STATE_ID, $user->getStateId());
    $this->setDefault(self::FIELD_POST_CODE, $user->getPostCode());
    $this->setDefault(self::FIELD_PHONE, $user->getPhone());
    $this->setDefault(self::FIELD_GENDER, $user->getGender());
    $this->setDefault(self::FIELD_DATE_OF_BIRTH, $user->getDateOfBirth());
    $this->setDefault(self::FIELD_CINEMA, $user->getPreferenceCinema());
    foreach (UserSignupForm::$moviePreferences as $key => $val) {
      $userMoviePreference = USER_MOVIE_PREFERENCETable::getInstance()->findByPreference($user->getId(), $key);
      if ($userMoviePreference instanceof USER_MOVIE_PREFERENCE) {
        $this->setDefault(self::FIELD_MOVIE_PREFERENCE . '_' . $key, true);
      }
    }
  }
}
?>